package class_wuziqi;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Chat_Server {
	private Socket socket;
	private ServerSocket server;
	private List<Socket> socket_list;
	private ExecutorService pool;
	private ChatRecord<String> chatRecord;
	public Chat_Server() {
		socket_list=new ArrayList<Socket>();
		chatRecord =new ChatRecord<String>();
		chatRecord.addPropertyChangeListener(new PropertyChangeListener() {
			@Override
			public void propertyChange(PropertyChangeEvent evt) {
				for (Socket socket : socket_list) {
					try {
						ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
						oos.writeObject(evt.getNewValue());
						oos.flush();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		pool=Executors.newFixedThreadPool(5);
		try {
			server =new ServerSocket(2727);
			System.out.println("服务器启动");
			while(true){
				socket=server.accept();
				chatRecord.add(socket.getInetAddress()+"加入游戏\n");
				socket_list.add(socket);
				pool.execute(new ServerReceive(socket, socket_list, chatRecord));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public static void main(String[] args) {
		new Chat_Server();
	}
}
